using UnityEngine;
using System.Collections;

/// <summary>
/// Manages the rotation and movement of the camera
/// using the player and the currentRoom of the player
/// </summary>
public class cameraMovement : MonoBehaviour 
{

    public GameObject player;

    private Transform myTransform;
    
    private const float ROTATION_SPEED = 5.0f;
    private const float Z_DISTANCE_TO_PLAYER = 10.0f;
	
    /// <summary>
    /// Initializes the camera and its attributes
    /// </summary>
	void Start () 
    {
        myTransform = transform;
	}
	
	/// <summary>
	/// Updates the camera each frame
	/// </summary>
	void Update () 
    {
        moveToPlayer();
        pointToPlayer();
	}

    /// <summary>
    /// Rotates the camera so it can look to the player
    /// </summary>
    private void pointToPlayer()
    {
        myTransform.rotation = Quaternion.Slerp(myTransform.rotation, 
                               Quaternion.LookRotation(player.transform.position - myTransform.position),
                               ROTATION_SPEED * Time.deltaTime);
    }

    /// <summary>
    /// Moves the camera so it can follow the player.
    /// However, it doesn't move if the camera 
    /// is near the end of the currentRoom
    /// </summary>
    private void moveToPlayer()
    {
        playerControls pc = (playerControls) player.GetComponent("playerControls");

        float newZ = player.transform.position.z - Z_DISTANCE_TO_PLAYER;

        if (!pc.isOnLimitsOfCurrentRoom())
            myTransform.position = new Vector3(player.transform.position.x,
                                    myTransform.position.y,
                                    newZ);
        else
            myTransform.position = new Vector3(myTransform.position.x,
                                    myTransform.position.y,
                                    newZ);
    }

}
